/*
 *  Filename: queue.c
 *  Function: Queue
 *  Created: 2017-04-10
 *  Version: 1.0
 *  Author: Bin
 */

/*-------- Includes --------*/
#include <stdlib.h>
#include "queue.h"

/*-------- Private defines --------*/
typedef struct node *link;
struct node {
    char *cmdStr;
    link prev, next;
};

/*-------- Private variables --------*/
struct node headsentinel;
struct node tailsentinel = {NULL, &headsentinel, NULL};
struct node headsentinel = {NULL, NULL, &tailsentinel};
static link head = &headsentinel;
static link tail = &tailsentinel;

/*-------- Private function prototypes --------*/
static void insert(link p);
static void delete(link p);
static int isEmpty();

/*-------- Exported functions --------*/
void Queue_Init()
{
    while (!isEmpty())
        delete(tail->prev);
}

void enQueue(char *element)
{
    link p = malloc(sizeof *p);

    p->cmdStr = element;
    insert(p);
}

char *deQueue()
{
    char *element;

    if (isEmpty()) {
        element = NULL;
    } else {
        element = tail->prev->cmdStr;
        delete(tail->prev);
    }

    return element;
}

/*--------Private functions --------*/
static void insert(link p)
{
    p->next = head->next;
    head->next->prev = p;
    head->next = p;
    p->prev = head;
}

static void delete(link p)
{
    p->prev->next = p->next;
    p->next->prev = p->prev;

    free(p);
}

static int isEmpty()
{
    return (tail->prev == head);
}
